package com.ls.filter;


import com.ls.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class LoginFilter implements GlobalFilter,Ordered {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        String path = request.getURI().getPath();
        log.debug("请求的路径为:{}",path);

        if (path.contains("/user/login")){
           return chain.filter(exchange);
        }

        //1、获取token（请求头中获取）
        String token = request.getHeaders().getFirst("Logintoken");
        //2、判断token是否为空,如果为则返回响应状态码401 未认证
        if (StringUtils.isEmpty(token)){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            //完成响应
            return exchange.getResponse().setComplete();
        }
        //3、判断redsi中是否存在这个token
        String redisToken = stringRedisTemplate.opsForValue().get("login:"+token);
        Claims claims = JwtUtil.parseJWT(token);
        System.out.println("claims:"+claims);
        Object username = claims.get("username");
        System.out.println("username:"+username);

        //4、如果不存在，直接返回401 未认证(没有登录)
        if (StringUtils.isEmpty(redisToken)){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
      //如果代码执行到这里,说明一定时登录状态，而且token时有效的

        //token续签
        stringRedisTemplate.opsForValue().set("login:"+token,token,1000L*30*60, TimeUnit.SECONDS);
        //5、如果存在，则放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 4;
    }
}
